import { Component, OnInit } from '@angular/core';
import { ControlApiService } from '@core/controlApi.service';
import { DatePipe } from '@angular/common';
import { ApiService } from '@core/api.service';
import { NzMessageService } from 'ng-zorro-antd';
import { DomSanitizer } from '@angular/platform-browser';
import { _HttpClient } from '@delon/theme';
import { environment } from '../../../../environments/environment';
declare const echarts: any;

@Component({
    selector: 'app-statdata',
    templateUrl: './statdata.component.html',
    styleUrls: ['./statdata.component.less']
})

export class ControlStatdataComponent implements OnInit {
    themeClass = 'whitetheme';
    treeNodeStyle = { 'max-width': '300px', 'max-height': '400px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
    selectClass = 'defaultSelect';

    clickLock = true;
    timeTips: any;
    timeText = '全部';
    step = '';
    oldstep = '';
    stationType = '';
    alarmQuestion = [];
    alarmAnalyseList = [];
    breadcrumb: any = {};
    dateTypeId = '';
    devTypeText = '';
    lineId = '';
    lineSelect: any = [];
    workshopId = '';
    workshopSelect: any = [];
    stationId = '';
    stationSelect: any = [];
    devTypeId = '';
    devTypeSelect: any = [];
    devNameId = '';
    devNameText = '';
    devNameSelect: any = [];
    startValue: any;
    endValue: any;

    constructor(
        private controlApiService: ControlApiService,
        private datePipe: DatePipe,
        private apiService: ApiService,
        private sanitizer: DomSanitizer,
        private http: _HttpClient,
        public msg: NzMessageService
    ) { }

    ngOnInit() {
        this.endValue = new Date().getTime();
        this.startValue = this.datePipe.transform(new Date, 'yyyy-MM') + '-01 00:00:00';
        // 默认显示所有车间
        this.step = 'workshop';
        this.getLine();
        this.getWorkshop();
        this.getDevType((res) => {
            // to do
        });

        echarts.init(document.getElementById('baojing')).on('click', (params) => {
            if (this.step == 'alarmtype') {
                return;
            }
            if (this.clickLock) {
                this.oldstep = this.step;
                this.clickLock = false;
                if (this.step === 'dev') {
                    // 展示具体设备报警原因
                    for (const item of this.devNameSelect) {
                        if (params.name == item.title) {
                            this.devNameId = item.key;
                            break;
                        }
                    }
                    if (this.devNameId == '') {
                        this.clickLock = true;
                        return;
                    }
                    this.devNameText = params.name;
                    this.updateBreadcrumb('devNameChange');
                    this.alarmSearch('echarts', 'alarmtype');
                    return;
                }
                if (this.step === 'devtype') {
                    // 展示所有设备列表
                    for (const item of this.devTypeSelect) {
                        if (item.children) {
                            for (const list of item.children) {
                                if (params.name == list.title) {
                                    this.devTypeId = list.key;
                                    break;
                                }
                            }
                        } else {
                            if (params.name == item.title) {
                                this.devTypeId = item.key;
                                break;
                            }
                        }
                    }
                    if (this.devTypeId == '') {
                        this.clickLock = true;
                        return;
                    }
                    this.getDevName(this.stationId, this.devTypeId, (res) => {
                        this.updateBreadcrumb('devTypeChange');
                        this.alarmSearch('echarts', 'dev');
                    });
                    return;
                }
                if (this.step == 'stationworkshop' || this.step == 'stationline') {
                    // 展示所有车站图表
                    for (const item of this.stationSelect) {
                        if (params.name == item.title) {
                            this.stationId = item.key;
                            break;
                        }
                    }
                    if (this.stationId == '') {
                        this.clickLock = true;
                        return;
                    }
                    this.updateBreadcrumb('stationChange');
                    this.alarmSearch('echarts', 'devtype');
                    return;
                }
                if (this.step == 'workshop') {
                    // 展示所有车间图表
                    for (const item of this.workshopSelect) {
                        if (params.name == item.title) {
                            this.workshopId = item.key;
                            break;
                        }
                    }
                    if (this.workshopId == '') {
                        this.clickLock = true;
                        return;
                    }
                    this.getStation(this.step, this.workshopId, (res) => {
                        this.updateBreadcrumb('workshopChange');
                        this.alarmSearch('', this.step);
                    });
                    return;
                }
                if (this.step == 'line') {
                    // 展示所有车线别图表
                    for (const item of this.lineSelect) {
                        if (params.name == item.title) {
                            this.lineId = item.key;
                            break;
                        }
                    }
                    if (this.lineId == '') {
                        this.clickLock = true;
                        return;
                    }
                    this.getStation(this.step, this.lineId, (res) => {
                        this.updateBreadcrumb('lineChange');
                        this.alarmSearch('', '');
                    });
                    return;
                }
            }
        });
    }
    // 更新面包屑
    updateBreadcrumb(type) {
        switch (type) {
            case 'lineChange':
                this.breadcrumb = {};
                this.breadcrumb.line = this.keyTotitle(this.lineSelect, this.lineId);
                this.timeText = this.breadcrumb.line;
                break;
            case 'workshopChange':
                this.breadcrumb = {};
                this.breadcrumb.workshop = this.keyTotitle(this.workshopSelect, this.workshopId);
                this.timeText = this.breadcrumb.workshop;
                break;
            case 'stationChange':
                this.breadcrumb.dev = false;
                this.breadcrumb.devtype = false;
                switch (this.stationType) {
                    case 'line':
                        this.breadcrumb.stationline = this.keyTotitle(this.stationSelect, this.stationId);
                        this.timeText = this.breadcrumb.stationline;
                        break;
                    case 'workshop':
                        this.breadcrumb.stationworkshop = this.keyTotitle(this.stationSelect, this.stationId);
                        this.timeText = this.breadcrumb.stationworkshop;
                        break;
                }
                break;
            case 'devTypeChange':
                this.breadcrumb.dev = false;
                this.breadcrumb.devtype = this.keyTotitle(this.devTypeSelect, this.devTypeId);
                this.timeText = this.breadcrumb.devtype;
                break;
            case 'devNameChange':
                this.breadcrumb.dev = this.keyTotitle(this.devNameSelect, this.devNameId);
                this.timeText = this.breadcrumb.dev;
                break;
        }
        this.timeTips = this.sanitizer.bypassSecurityTrustHtml('在 <span style="color:#ff0000;">' +
            this.datePipe.transform(this.startValue, 'yyyy-MM-dd HH:mm:ss') + ' - ' +
            this.datePipe.transform(this.endValue, 'yyyy-MM-dd HH:mm:ss') +
            '</span> 时间段内 <span style="color:#ff0000;">' +
            this.timeText + '</span> 的报警数量');
    }
    // 线别
    getLine() {
        this.controlApiService.getAllLines().subscribe((res: any) => {
            if (res.length != 0) {
                this.lineSelect = this.formatOpName(res);
            } else {
                this.clickLock = true;
            }
        });
    }
    lineChange(e) {
        this.clickLock = false;
        this.step = 'line';
        this.workshopId = '';
        // 更新面包屑
        this.updateBreadcrumb('lineChange');
        // 清空子数据
        this.clearChild();
        this.getStation(this.step, this.lineId, (res) => {
            // to do
        });
    }
    // 车间
    getWorkshop() {
        this.apiService.getAllChejian('0').subscribe((res: any) => {
            if (res.length) {
                this.workshopSelect = this.formatOpName(res);
                this.alarmSearch('', this.step);
            } else {
                this.clickLock = true;
            }
        });
    }
    workshopChange(e) {
        this.clickLock = false;
        this.step = 'workshop';
        this.lineId = '';
        // 更新面包屑
        this.updateBreadcrumb('workshopChange');
        // 清空子数据
        this.clearChild();
        this.getStation(this.step, this.workshopId, (res) => {
            // to do
        });
    }
    // 车站名称
    getStation(type, id, callback) {
        if (type == '' || id == '') {
            return;
        }
        this.stationType = type;
        this.stationId = '';
        this.stationSelect = [];
        switch (type) {
            case 'line':
                this.getStationByLine(id).subscribe((res: any) => {
                    this.stationSelect = this.formatIdname(res);
                    this.step = 'stationline';
                    callback(res);
                });
                break;
            case 'workshop':
                this.getStationByWorkshop(id).subscribe((res: any) => {
                    this.stationSelect = this.formatIdname(res);
                    this.step = 'stationworkshop';
                    callback(res);
                });
                break;
        }
    }

    // 车间获取车站
    getStationByWorkshop(workshopid) {
        const url = environment.apiBase + '/csmis/stations/getStationByWorkshop.jwt?workshopid=' + workshopid;
        return this.http.get(url);
    }
    // 线别获取车站
    getStationByLine(lineid) {
        const url = environment.apiBase + '/csmis/stations/getStationByLine.jwt?lineid=' + lineid;
        return this.http.get(url);
    }
    stationChange(e) {
        this.clickLock = false;
        this.step = 'devtype';
        // 更新面包屑
        this.updateBreadcrumb('stationChange');
        // 清空子数据
        this.clearChild();
    }
    // 设备类型
    getDevType(callback) {
        this.getAllDevType().subscribe((res: any) => {
            if (res.length) {
                const level1 = [];
                const level2 = [];
                for (const item of res) {
                    switch (item.NLEVEL) {
                        case 1:
                            level1.push({
                                key: item.CODE,
                                title: item.TYPENAME,
                                children: []
                            });
                            break;
                        case 2:
                            level2.push(item);
                            break;
                    }
                }
                for (const item of level1) {
                    for (const list of level2) {
                        if (item.key == list.PARENTID) {
                            item.children.push({
                                key: list.CODE,
                                title: list.TYPENAME,
                                isLeaf: true
                            });
                        }
                    }
                }
                this.devTypeSelect = level1;
            }
            callback(res);
        });
    }

    // 综合报警设备类型
    getAllDevType() {
        const url = environment.apiBase + '/csmis/alert/getAllDevType.jwt';
        return this.http.post(url);
    }
    devTypeChange(e) {
        this.clickLock = false;
        this.step = 'dev';
        this.devTypeText = this.keyTotitle(this.devTypeSelect, this.devTypeId);
        // 更新面包屑
        this.updateBreadcrumb('devTypeChange');
        // 清空子数据
        this.devNameId = '';
        this.devNameText = '';
        this.devNameSelect = [];
        this.getDevName(this.stationId, this.devTypeId, (res) => {
            // to do
        });
    }
    // 设备名称
    getDevName(stationId, devTypeId, callback) {
        if (!stationId || !devTypeId) {
            return;
        }
        this.controlApiService.getDevByStationType(stationId, devTypeId).subscribe((res: any) => {
            if (res.type === 'success') {
                const data = res.response.data;
                if (data.length) {
                    for (const item of data) {
                        this.devNameSelect.push({
                            title: item.VC_NAME,
                            key: item.ID,
                            isLeaf: true
                        });
                    }
                } else {
                    this.clickLock = true;
                }
                callback(res);
            }
        });
    }
    devNameChange(e) {
        if (!this.stationId) {
            this.msg.error('请先选择车站后，再选择设备', { nzDuration: 1000 });
            return;
        }
        if (!this.devTypeId) {
            this.msg.error('请先选择设备类型后，再选择设备', { nzDuration: 1000 });
            return;
        }
        this.devNameText = this.keyTotitle(this.devNameSelect, this.devNameId);
        // 更新面包屑
        this.updateBreadcrumb('devNameChange');
        this.step = 'alarmtype';
        for (const item of this.devNameSelect) {
            if (e == item.key) {
                this.devNameText = item.title;
                break;
            }
        }
    }
    // 根据key找title
    keyTotitle(data, key) {
        let title = '';
        for (const item of data) {
            if (item.children) {
                for (const list of item.children) {
                    if (list.key == key) {
                        title = list.title;
                        return title;
                    }
                }
            } else {
                if (item.key == key) {
                    title = item.title;
                    return title;
                }
            }
        }
    }
    breadcrumbClick(step) {
        this.clickLock = true;
        switch (step) {
            case 'all':
                this.alarmReset();
                break;
            case 'line':
            case 'workshop':
                if (step == 'line') {
                    this.step = 'stationline';
                    this.timeText = this.breadcrumb.line;
                }
                if (step == 'workshop') {
                    this.step = 'stationworkshop';
                    this.timeText = this.breadcrumb.workshop;
                }
                this.breadcrumb.stationline = false;
                this.breadcrumb.stationworkshop = false;
                this.breadcrumb.devtype = false;
                this.breadcrumb.dev = false;
                this.stationId = '';
                this.devTypeId = '';
                this.devTypeText = '';
                this.devNameSelect = [];
                this.devNameId = '';
                this.devNameText = '';
                break;
            case 'stationline':
            case 'stationworkshop':
                this.step = 'devtype';
                this.breadcrumb.devtype = false;
                this.breadcrumb.dev = false;
                this.devTypeId = '';
                this.devTypeText = '';
                this.devNameSelect = [];
                this.devNameId = '';
                this.devNameText = '';
                if (step == 'stationline') {
                    this.timeText = this.breadcrumb.stationline;
                } else {
                    this.timeText = this.breadcrumb.stationworkshop;
                }
                break;
            case 'devtype':
                this.step = 'dev';
                this.breadcrumb.dev = false;
                this.devNameSelect = [];
                this.devNameId = '';
                this.devNameText = '';
                this.timeText = this.breadcrumb.devtype;
                break;
            case 'dev':
                this.timeText = this.breadcrumb.dev;
                break;
        }
        this.alarmSearch('', this.step);
    }
    alarmSearch(setType, setStep) {
        this.clickLock = true;
        let formatDevTypeId = '';
        let formatDevName = '';
        if (setType == 'echarts') {
            this.step = setStep;
        }
        const startTime = this.datePipe.transform(this.startValue, 'yyyy-MM-dd HH:mm:ss');
        const endTime = this.datePipe.transform(this.endValue, 'yyyy-MM-dd HH:mm:ss');
        this.timeTips = this.sanitizer.bypassSecurityTrustHtml('在 <span style="color:#ff0000;">' +
            startTime + ' - ' + endTime + '</span> 时间段内 <span style="color:#ff0000;">' +
            this.timeText + '</span> 的报警数量');
        // 画图
        if (setStep == 'dev' || setStep == 'alarmtype') {
            this.controlApiService.getDevname(this.stationId, this.devTypeId, '', this.devTypeText, this.devNameText, '1', (devname) => {
                // 转设备类型和设备名
                if (devname != '[]') {
                    devname = JSON.parse(devname);
                    formatDevTypeId = devname[0].B_DEVTYPEID;
                    formatDevName = devname[0].B_DEVNAME;
                    // 按报警类别统计
                    this.alarmAnalyse(this.lineId, this.workshopId, this.stationId, formatDevTypeId, formatDevName, this.step, startTime, endTime, (resAnalyse) => {
                        // 按报警时间统计
                        this.alarmTime(resAnalyse, this.lineId, this.workshopId, this.stationId, formatDevTypeId, formatDevName, startTime, endTime);
                    });
                } else {
                    this.step = this.oldstep;
                    this.msg.error('未找到该监测设备关联的调度中心系统设备，请检查是否成功配置！', { nzDuration: 2000 });
                }
            });
        } else {
            // 按报警类别统计
            this.alarmAnalyse(this.lineId, this.workshopId, this.stationId, formatDevTypeId, formatDevName, this.step, new Date(startTime).getTime(), new Date(endTime).getTime(), (resAnalyse) => {
                // 按报警时间统计
                this.alarmTime(resAnalyse, this.lineId, this.workshopId, this.stationId, formatDevTypeId, formatDevName, new Date(startTime).getTime(), new Date(endTime).getTime());
            });
        }
    }
    alarmAnalyse(lineId, workshopId, stationId, formatDevTypeId, formatDevName, step, startTime, endTime, callback) {
        this.alarmAnalyseData(lineId, workshopId, stationId, formatDevTypeId, formatDevName, step, startTime, endTime).subscribe((resAnalyse: any) => {
            this.alarmAnalyseList = resAnalyse.data[0];
            if (resAnalyse.data[0].lenght === 0) {
                this.msg.error('报警统计数据为空，请选择其他选项', { nzDuration: 1000 });
                this.clickLock = true;
            }
            callback(resAnalyse);
        });
    }
    alarmTime(resAnalyse, lineId, workshopId, stationId, formatDevTypeId, formatDevName, startTime, endTime) {
        const getname = [];
        const getdata = [];
        const gettime = [];
        const gettdata = [];
        this.alarmAnalyseByTime(lineId, workshopId, stationId, formatDevTypeId, formatDevName, startTime, endTime).subscribe((resTime: any) => {
            if (resTime.msg === 'Ok') {
                if (resTime.data[0].lenght) {
                    for (const item of resTime.data[0]) {
                        gettime.push(item.TIME);
                        gettdata.push(item.C);
                    }
                    for (const item of resAnalyse.data[0]) {
                        getname.push(item.NAME);
                        getdata.push(item.C);
                    }
                } else {
                    this.msg.error('报警时间数据为空，请选择其他选项', { nzDuration: 1000 });
                }
                this.eleSearch('baojing', '213,113,62', getname, getdata, '');
                this.eleSearch('shijian', '51,152,219', gettime, '', gettdata);
                this.clickLock = true;
            }
        });
    }
    // 综合报警分析
    alarmAnalyseData(lineid, workshopid, stationid, devtypeid, devname, type, begintime, endtime) {
        let url = environment.project + '/alarmTab2/alarmAnalyse?type=' + type + '&begintime=' + begintime + '&endtime=' + endtime;
        workshopid ? url += '&workshopid=' + workshopid : url += '';
        lineid ? url += '&lineid=' + lineid : url += '';
        stationid ? url += '&stationid=' + stationid : url += '';
        devtypeid ? url += '&devtypeid=' + devtypeid : url += '';
        devname ? url += '&devname=' + devname : url += '';
        return this.http.get(url);
    }
    // 综合报警时间分析
    alarmAnalyseByTime(lineid, workshopid, stationid, devtypeid, devname, begintime, endtime) {
        let url = environment.project + '/alarmTab2/alarmAnalyseByTime?begintime=' + begintime + '&endtime=' + endtime;
        lineid ? url += '&lineid=' + lineid : url += '';
        workshopid ? url += '&workshopid=' + workshopid : url += '';
        stationid ? url += '&stationid=' + stationid : url += '';
        devtypeid ? url += '&devtypeid=' + devtypeid : url += '';
        devname ? url += '&devname=' + devname : url += '';
        return this.http.get(url);
    }
    alarmReset() {
        this.timeText = '全部';
        this.clickLock = true;
        // 清空子数据
        this.lineId = '';
        this.workshopId = '';
        this.stationId = '';
        this.stationSelect = [];
        this.devTypeId = '';
        this.devTypeText = '';
        this.devNameId = '';
        this.devNameText = '';
        this.devNameSelect = [];
        this.step = 'workshop';
        // 更新面包屑
        this.breadcrumb = {};
        this.alarmSearch('', this.step);
    }
    // 清空子数据
    clearChild() {
        this.devTypeId = '';
        this.devTypeText = '';
        this.devNameId = '';
        this.devNameText = '';
        this.devNameSelect = [];
    }
    formatOpName(resdata) {
        const node: any = [];
        for (const item of resdata) {
            node.push({
                title: item.opName,
                key: item.opValue,
                isLeaf: true
            });
        }
        return node;
    }
    formatIdtext(resdata) {
        const node: any = [];
        let count = 0;
        for (const item of resdata) {
            if (item.children) {
                node.push({
                    title: item.text,
                    key: item.id,
                    disabled: true,
                    children: []
                });
                for (const list of item.children) {
                    node[count].children.push({
                        title: list.text,
                        key: list.id,
                        isLeaf: true
                    });
                }
            } else {
                node.push({
                    title: item.text,
                    key: item.id,
                    isLeaf: true
                });
            }
            count += 1;
        }
        return node;
    }
    formatIdname(resdata) {
        const node: any = [];
        if (resdata.type === 'success') {
            const data = resdata.response.data;
            if (data.length) {
                for (const item of data) {
                    node.push({
                        title: item.STATIONNAME,
                        key: item.STATIONID,
                        isLeaf: true
                    });
                }
            }
        }
        return node;
    }
    themeChenge(e) {
        this.themeClass = e;
    }
    eleSearch(id, color, getname, getdata, gettdata) {
        let seriesType = 'bar';
        let setbarWidth = 30;
        let seriesStep = '';
        let tooltipType: any = { trigger: 'item' };
        if (id === 'shijian') {
            getdata = gettdata;
            seriesType = 'line';
            seriesStep = 'end';
            tooltipType = { trigger: 'axis', axisPointer: { type: 'cross', label: { backgroundColor: 'rgba(' + color + ', 1)' } } };
        }
        if (getdata.length > 50 && getdata.length < 100) {
            setbarWidth = 10;
        }
        if (getdata.length >= 100) {
            setbarWidth = 3;
        }
        echarts.init(document.getElementById(id)).setOption({
            color: [
                new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(' + color + ', 1)'
                }, {
                    offset: 1,
                    color: 'rgba(' + color + ', 0.5)'
                }])
            ],
            tooltip: tooltipType,
            xAxis: [{
                'data': getname
            }],
            yAxis: [
                {
                    'type': 'value'
                }
            ],
            grid: {
                'left': 60,
                'right': 0,
                'top': 30,
                'bottom': 20
            },
            series: [
                {
                    name: '报警数量',
                    type: seriesType,
                    areaStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgba(' + color + ', 1)'
                            }, {
                                offset: 1,
                                color: 'rgba(' + color + ', 0.5)'
                            }])
                        }
                    },
                    step: seriesStep,
                    barWidth: setbarWidth,
                    data: getdata,
                    label: {
                        normal: {
                            show: true,
                            position: 'top',
                            fontSize: 18,
                            textBorderColor: '#fff',
                            textBorderWidth: 3,
                        }
                    }
                }
            ]
        }, true);
        this.clickLock = true;
    }
}
